package com.cuz.hot100;

public class Q29DivideTwoNumbers {
    public static void main(String[] args) {
//        System.out.println(divide1(10, 3));
//        System.out.println(divide1(-10, 3));
//        System.out.println(divide1(-10, -3));
//        System.out.println(divide1(10, -3));
//        System.out.println(divide1(1, -3));
//        System.out.println(divide1(-1, -3));
        //-2147483648
        //-1
        System.out.println(divide1(-2147483648, 2));
    }

    public static int divide1(int dividend, int divisor) {
        if (dividend == 0) {
            return 0;
        }
        if (divisor == 1) {
           return dividend;
        }
        if (divisor == -1) {
            if (dividend > Integer.MIN_VALUE) {
                return -dividend;
            }
            return Integer.MAX_VALUE;
        }
        boolean diff = (dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0);
        long dividendLong = Math.abs((long) dividend);
        long divisorLong = Math.abs((long)divisor);
        long res = div(dividendLong, divisorLong);
        if (!diff) {
            return (int) Math.min(res, Integer.MAX_VALUE);
        }
        return (int) -res;
    }


    private static long div(long dividendLong, long divisorLong) {
        //3/10==>0
        if (dividendLong < divisorLong) {
            return 0;
        }
        int count = 1;
        long temp = divisorLong;
        // 16 /3===>6<16(count=2 至少两倍)  12<16(至少四倍)  24>16（不行没有8倍）
        while ((temp + temp) <= dividendLong) {
            count = count + count;
            temp = temp + temp;
        }
        //4+  （16-12=4）/3===》1倍===》5
        return count + div(dividendLong - temp, divisorLong);
    }

}
